// JavaScript Document

var status;
var orderData;
var browser;
var userId;
var uuid;
var isSeller;
var buyerName;
var ajaxLock;

var wxInstall;
var jsApiParameters;

function showOrder(_orderData) {

  orderData = _orderData;
  status = orderData.status;
    
  statusBar();
  quantity();
  contact();
  totalFee();
  express();
  actionButton();
  statusList();
}


// 状态栏
function statusBar() {
  $statusBar = $('.status-bar');
  if (isSeller) {
    
    if (status == '询问中' ) {
      $statusBar.hide();
    } else if (status == '待确认') {
      $statusBar.show();
      $statusBar.html(buyerName + '预约了'+ orderData.quantity +'份，等待确认');
    } else if (status == '已关闭') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('交易已关闭');
    } else if (status == '待支付') {
      $statusBar.html('已同意'+ buyerName + '的预约，等待付款');
    } else if (status == '已支付') {
      $statusBar.html(buyerName +'已经付款' + showFee(orderData.totalFee) +'等待发货');
    } else if (status == '已发货') {
      $statusBar.html('已发出，等待买家确认');
    } else if (status == '已退款') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('已完成退款');
    } else if (status == '交易成功') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('订单已完成');
    } else {
      $('.status-bar').hide();
    }
    
  } else {
    
    if (status == '询问中' ) {
      $statusBar.hide();
    } else if (status == '待确认') {
      $statusBar.show();
      $statusBar.html('预约申请已发出，等待卖家确认');
    } else if (status == '已关闭') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('交易已关闭');
    } else if (status == '待支付') {
      $statusBar.html('预约成功，卖家修改价格为' + showFee(orderData.totalFee) + '元，等待付款');
    } else if (status == '已支付') {
      $statusBar.html('已经付款，等待卖家发货');
    } else if (status == '已发货') {
      $statusBar.html('卖家已发货，等待收货后确认付款');
    } else if (status == '已退款') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('退款成功，请查看你的余额');
    } else if (status == '交易成功') {
      $statusBar.removeClass('status-bar-blue');
      $statusBar.html('订单已完成，记得晒单哦');
    } else {
      $('.status-bar').hide();
    }
    
  }

}

// 订单数量
function quantity() {
  $quantity = orderData.quantity;
  if ($quantity == 0) $quantity = 1;
  $quantityInput = $('#quantity input');
  $quantityValue = $('#quantity .value');
  $quantityInput.val($quantity);
  $quantityValue.html($quantity);
  
  if (isSeller) {
    $quantityInput.hide();
    $quantityValue.show();
  } else {
    if (status == '询问中' ) {
      $quantityInput.show();
      $quantityValue.hide();
    } else if (status == '待确认') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '已关闭') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '待支付') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '已支付') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '已发货') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '已退款') {
      $quantityInput.hide();
      $quantityValue.show();
    } else if (status == '交易成功') {
      $quantityInput.hide();
      $quantityValue.show();
    } else {
      $quantityInput.hide();
      $quantityValue.show();
    }
  }
}

// 联系信息
function contact() {
  $('#req_name input').val(orderData.req_name);
  $('#req_mobile input').val(orderData.req_mobile);
  $('#req_address textarea').val(orderData.req_address);
  $('#req_name span').html(orderData.req_name);
  $('#req_mobile span').html(orderData.req_mobile);
  $('#req_address span').html(orderData.req_address);
  
  if (!isSeller) {
    if (!orderData.req_name || !orderData.req_mobile || !orderData.req_address) {
      $('#contact #modify').html('添加邮寄信息');
    } 
  }
  
  $button = $('#contact #modify');
  
  if (isSeller) {
    
    $button.hide();
    contactStatus('span');
  } else {
    
    if (status == '询问中' ) {
      $button.show();
      contactStatus('span');
    } else if (status == '待确认') {
      $button.hide();
      contactStatus('span');
    } else if (status == '已关闭') {
      $button.hide();
      contactStatus('span');
    } else if (status == '待支付') {
      $button.hide();
      contactStatus('span');
    } else if (status == '已支付') {
      $button.hide();
      contactStatus('span');
    } else if (status == '已发货') {
      $button.hide();
      contactStatus('span');
    } else if (status == '已退款') {
      $button.hide();
      contactStatus('span');
    } else if (status == '交易成功') {
      $button.hide();
      contactStatus('span');
    } else {
      $button.hide();
      contactStatus('span');
    }
  }
}

// 联系信息动作控制
function contactStatus(type){
  if (type == 'input') {
    $('#contact #modify').hide();
    $('#contact span').hide();
    
    $('#contact input').show();
    $('#contact textarea').show();
    $('#contact #confirm').show();
  } else {
    $('#contact span').show();
    
    $('#contact input').hide();
    $('#contact textarea').hide();
    $('#contact #confirm').hide();
  }
}

// 合计
function totalFee() {
  $('#totalFee .price').html(showFee(orderData.totalFee));
}

// 快递
function express() {
  if(orderData.express) {
    $('#express .value').html(orderData.express);
  } else {
    $('#express').hide();
  }
}

// action-button
function actionButton() {
  $main = $('.action-button #main');
  $cancel = $('.action-button #cancel');
  $disable = $('.action-button #disable');
  $disable.hide();
  
  $main.html('立即预约').show();;
  
  if (isSeller) {
      
    if (status == '询问中' ) {
      $main.hide();
      $cancel.hide();
      $disable.html('等待买家预约').show();
    } else if (status == '待确认') {
      $main.html('同意预约申请').show();
      $cancel.html('拒绝申请').show();
      $disable.hide();
    } else if (status == '已关闭') {
      $main.hide();
      $cancel.hide();
    } else if (status == '待支付') {
      $main.hide();
      $cancel.hide();
      $disable.html('等待买家付款').show();
    } else if (status == '已支付') {
      $main.html('确认发货').show();;
      $cancel.hide();
      $disable.hide();
    } else if (status == '已发货') {
      $main.hide();
      $cancel.hide();
      $disable.html('等待买家收货').show();
    } else if (status == '已退款') {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    } else if (status == '交易成功') {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    } else {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    }
  
  } else {
    
    if (status == '询问中' ) {
      $main.html('立即预约').show();;
      $cancel.html('取消').hide();;
      $disable.hide();
    } else if (status == '待确认') {
      $main.hide();
      $cancel.html('取消预约').show();
      $disable.hide();
    } else if (status == '已关闭') {
      $main.hide();
      $cancel.hide();
      $disable.hide();
    } else if (status == '待支付') {
      $main.html('立即支付');
      $cancel.html('取消');
      $disable.hide();
    } else if (status == '已支付') {
      $main.hide();
      $cancel.hide();
      $disable.html('等待卖家发货').show();
    } else if (status == '已发货') {
      $cancel.hide();
      $main.html('确认收货');
      $disable.hide();
    } else if (status == '已退款') {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    } else if (status == '交易成功') {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    } else {
      $cancel.hide();
      $main.hide();
      $disable.hide();
    }
    
  }

}

// 订单状态
function statusList() {
  
  $('.status-list #step1 span').html(showDate(orderData.created));
  $('.status-list #step2 span').html(showDate(orderData.requestTime));
  $('.status-list #step3 span').html(showDate(orderData.confirmTime));
  $('.status-list #step4 span').html(showDate(orderData.payTime));
  $('.status-list #step5 span').html(showDate(orderData.shipTime));
  //$('.status-list #step6 span').html(orderData.status);
  
  var step = 0;
  
  if (status == '询问中' ) {
    step = 1;
  } else if (status == '待确认') {
    step = 2;
  } else if (status == '已关闭') {
    step = 2;
  } else if (status == '待支付') {
    step = 3;
  } else if (status == '已支付') {
    step = 4;
  } else if (status == '已发货') {
    step = 5;
  } else if (status == '已退款') {
    step = 5;
  } else if (status == '交易成功') {
    step = 6;
  } else {
    step = 0;
  }
  $('.status-list .active').removeClass('active');
  $('.status-list .todo').removeClass('todo');
  
  for (var i = step; i<7; i++){
    if (step == i) {
      $('.status-list #step' + i).addClass('active');
    } else {
      $('.status-list #step' + i).addClass('todo');
    }
  }
}


// AJAX 部分

// 数量
$('#quantity input').blur(function (){
  _val = $(this).val();
  postData('/buy/ajax/', {orderid:orderData.id, type:'quantity', value:_val});
});

// 联系信息
function postContact(){
  var req_name = $('#contact #req_name input').val();
  var req_mobile = $('#contact #req_mobile input').val();
  var req_address = $('#contact #req_address textarea').val();
  if (!req_name || !req_mobile || !req_address) {
    alert('没有完整填写邮寄信息');
    return;
  }
  postData('/buy/ajax/', {orderid:orderData.id, type:'contact', req_name:req_name, req_mobile:req_mobile, req_address:req_address});
};

// 按钮请求
function mainButton() {
  
  if (isSeller) {
    
    if (status == '待确认') {
      var m = prompt ( "请输入最终价格" , orderData.totalFee / 100) ;
      if (m >= 0.01) {
        postData('/buy/action/', {orderid:orderData.id, a:'confirm', value:m});
      } else if (m == 0) {
        alert('价格不能为0');
      }
    } else if (status == '已支付') {
      postData('/buy/action/', {orderid:orderData.id, a:'ship'});
    }
    
  } else {
    
    if (status == '询问中') {
      if (!orderData.req_name || !orderData.req_mobile || !orderData.req_address) {
        alert('请填写邮寄信息');
        contactStatus('input');
        return;
      }
      postData('/buy/request/', {orderid:orderData.id});
      
    } else if (status == '待支付') {
      if (browser == 'weixin') {
        $('#payment #alipay').show();
        $('#payment #wx').show();
        $('#payment').fadeIn();
      } else if (browser == 'matcha') {
        if (wxInstall == 1) {
          $('#payment #wxapp').show();
          $('#payment #alipayapp').show();
          $('#payment').fadeIn();
        } else {
          document.location = "matcha-web-call://pay/alipay/" + orderData.id;
        }
      } else {
        $('#payment #alipay').show();
        $('#payment').fadeIn();
      }
      
    } else if (status == '已发货') {
      postData('/buy/action/', {orderid:orderData.id, a:'done'});
    }
    
  }
}

$('.close').click(function (){
  $('#payment').fadeOut();
});

$('#payment #alipay button').click(function (){
  document.location = "/buy/pay/?type=alipay&ids=" + orderData.id + "&uuid=" + uuid;
});

$('#payment #wx button').click(function (){
  if (ajaxLock == 1) return;
  ajaxLock = 1;
  $('.pop-info').html('加载中').fadeIn();
  $.post("/buy/pay/?type=wx&ids=" + orderData.id + "&uuid=" + uuid, '', function(result){
    if (result == 'NO OPENID' && result == '请先登录') {
      $('.pop-info').html('请在微信中打开本网页').fadeIn();;
    } else {
      jsApiParameters = $.parseJSON(result);
      $('.pop-info').fadeOut();
      callpay();
    }
  });
  ajaxLock = 0;
});

$('#payment #alipayapp button').click(function (){
  document.location = "matcha-web-call://pay/alipay/" + orderData.id;
});

$('#payment #wxapp button').click(function (){
  document.location = "matcha-web-call://pay/wxpay/" + orderData.id;
});

// 取消按钮

function cancelButton() {
  postData('/buy/action/', {orderid:orderData.id, a:'cancel'});
}


function postData(postLink, postData) {
  if (ajaxLock == 1) return;
  ajaxLock = 1;
  $.post(postLink + '?uuid=' + uuid, postData, function(result){
    data = $.parseJSON(result);
    $('.pop-info').fadeIn();
    if(data.succ == 1) {
      setTimeout("getOrder();", 1000);
    } else {
      $('.pop-info').html(data.msg);
    }
    //console.log(result);
  });
  setTimeout("$('.pop-info').fadeOut();", 1000);
  ajaxLock = 0;
}


// 通用函数

function getOrder() {
  $.post("/buy/ajax/?uuid=" + uuid,{orderid:orderData.id},function(result){
    setOrder( $.parseJSON(result) );
  });
}

function setOrder(order) {
   showOrder(order);
}

function showFee(fee) {
  return '￥' + (fee / 100);
}

function showDate(unix) {
  if (!unix || unix == 0) {
    result = '';
  } else {
    var now = new Date(parseInt(unix) * 1000);
    result = now.toLocaleDateString().replace(/\//g, "-") + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(); 
  }

  return result;
}

function setData(data) {
  browser = data.browser;
  uuid = data.uuid;
  userId = data.userId;
  isSeller = data.isSeller;
  buyerName = data.buyerName;
}

function setWxInstall(isInstall) {
  wxInstall = isInstall;
}



//调用微信JS api 支付
function jsApiCall() {
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    jsApiParameters,
    function(res){
      WeixinJSBridge.log(res.err_msg);
      if( res.err_msg.indexOf("ok") >= 0 ) {
        location.reload();
      } else if (res.err_msg.indexOf("fail") >= 0) {
        alert('请尝试使用其他支付方式');
      }
    }
  );
}

function callpay() {
  if (typeof WeixinJSBridge == "undefined"){
    if( document.addEventListener ){
        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
    } else if (document.attachEvent){
        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
    }
  } else {
    jsApiCall();
  }
}